package com.kzw.oa.system.web;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kzw.core.bean.Msg;
import com.kzw.core.mapper.Jackson;
import com.kzw.core.orm.Page;
import com.kzw.core.orm.PageRequest;
import com.kzw.core.orm.StringPropertyFilter;
import com.kzw.core.util.BeanUtil;
import com.kzw.core.util.ExportUtil;
import com.kzw.core.util.ExtjsUtil;
import com.kzw.core.util.StringUtil;
import com.kzw.core.util.XML2JSON;
import com.kzw.core.util.json.JSON;
import com.kzw.core.util.web.ResponseUtils;
import com.kzw.misc.utils.AppUtil;
import com.kzw.oa.system.model.AppRole;
import com.kzw.oa.system.service.AppRoleService;

@Controller
@RequestMapping("/system/role")
public class AppRoleAction {

	@Autowired
	private AppRoleService appRoleService;

	private static String IS_COPY = "1";

	@RequestMapping("index")
	public String index() {
		return "system/role_view";
	}
	
	/**
	 * 显示列表
	 */
	@RequestMapping("list")
	public void list(HttpServletRequest request, HttpServletResponse response) {

		PageRequest pageRequest = ExtjsUtil.getPageReq(request);
		List<StringPropertyFilter> filters = ExtjsUtil.getFilters(request);
		Page<AppRole> page = appRoleService.search2(pageRequest, filters);
		
		// 是否导出

		String json = new JSON(page).buildWithFilters(3, "appUsers", "functions", "rights");
		ResponseUtils.renderJson(response, json);
	}
	
	/**
	 * 角色授权
	 */
	@ResponseBody
	@RequestMapping("grant")
	public Msg grant(Long roleId, HttpServletRequest request) {
		AppRole appRole = appRoleService.get(roleId);
		String rights = request.getParameter("rights");
		if (rights == null) {
			rights = "";
		}

		if (!rights.equals(appRole.getRights())) {
			appRole.setRights(rights);
			// 检查Right是否发生了变化
			appRoleService.saveOrUpdate(appRole);
			// 重新加载权限 优化为只是更新该角色对应的权限
			// AppUtil.reloadSecurityDataSource();
		}
		return new Msg(true);
	}
	
	/**
	 * 加载授权的XML，设置选中？
	 */
	@ResponseBody
	@RequestMapping("grantXml")
	public void grantXml(Long roleId, HttpServletResponse response) {
		Document grantMenuDoc = AppUtil.getGrantMenuDocument();
		String json = XML2JSON.parse(grantMenuDoc.asXML());
		json = json.replace("Modules", "data").replace("Menus", "trees")
				.replace("Items", "list").replace("Item", "list")
				.replace("text", "name").replace("\"id", "\"value");
		
		AppRole role = appRoleService.get(roleId);
		String rights = role.getRights();
		if(StringUtils.isNotBlank(rights)) {
			String[] arr = rights.split(",");
			for(String txt : arr) {
				json = json.replace("\"value\":\""+txt+"\"", "\"value\":\""+txt+"\", \"checked\":true");
			}
		}
		
		ResponseUtils.renderJson(response, json);
	}

	/**
	 * 列出角色树
	 */
	@RequestMapping("tree")
	public void tree(HttpServletResponse response) {
		List<AppRole> listRole;
		StringBuffer buff = new StringBuffer("[");
		listRole = appRoleService.getAll();// 最顶层父节点
		for (AppRole role : listRole) {
			buff.append("{id:'" + role.getRoleId() + "',text:'" + role.getRoleName() + "',leaf:true},");
		}
		if (!listRole.isEmpty()) {
			buff.deleteCharAt(buff.length() - 1);
		}
		buff.append("]");
		ResponseUtils.renderJson(response, buff.toString());
	}

	/**
	 * iframe页面
	 */
	@RequestMapping("html/add")
	public String addUi() {
		return "system/role_form";
	}
	
	@RequestMapping("html/edit")
	public String editUi(Long roleId, Model model) {
		AppRole role = appRoleService.get(roleId);
		model.addAttribute("role", role);
		return "system/role_form";
	}

	@RequestMapping("html/grant")
	public String grantUi(Long roleId, Model model) {
		AppRole role = appRoleService.get(roleId);
		model.addAttribute("role", role);
		return "system/role_grant_form";
	}
	
	/**
	 * 批量删除
	 */
	@RequestMapping("multiDel")
	@ResponseBody
	public Msg multiDel(String[] ids) {
		if (ids != null) {
			appRoleService.multiDel(ids);
		}
		
		return new Msg(true);
	}

	/**
	 * 显示详细信息
	 */
	@RequestMapping("get")
	public void get(Long roleId, HttpServletResponse response) {
		AppRole appRole = appRoleService.get(roleId);

		// 将数据转成JSON格式
		StringBuffer sb = new StringBuffer("{success:true,data:");
		sb.append(new JSON(appRole, true).buildWithFilters(3, "appUsers", "functions"));
		sb.append("}");

		ResponseUtils.renderJson(response, sb.toString());
	}

	/**
	 * 添加及保存操作 当是isCopy='1'时，则是为角色的复制
	 */
	@ResponseBody
	@RequestMapping("save")
	public Msg save(AppRole appRole, String isCopy) {
		if (StringUtils.isNotEmpty(isCopy) && IS_COPY.equals(isCopy)) {
			AppRole role = new AppRole();
			role.setRoleDesc(appRole.getRoleDesc());
			role.setStatus(appRole.getStatus());
			role.setRoleName(appRole.getRoleName());
			appRole = appRoleService.get(appRole.getRoleId());
			//Set<AppFunction> set = new HashSet<AppFunction>(appRole.getFunctions());
			//role.setFunctions(set);
			role.setRights(appRole.getRights());
			appRoleService.saveOrUpdate(role);
		} else {
			if(appRole.getStatus() == null) {
				appRole.setStatus(0);
			}
			if (appRole.getRoleId() == null) {
				appRoleService.saveOrUpdate(appRole);
			} else {
				AppRole orgRole = appRoleService.get(appRole.getRoleId());
				try {
					BeanUtil.copyNotNullProperties(orgRole, appRole);
					appRoleService.saveOrUpdate(orgRole);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		}
		return new Msg(true);
	}

	@RequestMapping("check")
	@ResponseBody
	public Msg check(String roleName) {
		Msg msg = new Msg();
		AppRole appRole = appRoleService.findUniqueBy("roleName", roleName);
		if (appRole != null) {
			msg.setSuccess(false);
		}
		return msg;
	}
	
	/**
	 * 关联下拉
	 */   	
	@RequestMapping("combo")
	public void combo(HttpServletResponse response) {
		List<AppRole> list = appRoleService.getAll();
		String json = Jackson.me().with(AppRole.class, "roleId", "roleName").toJson(list);
		ResponseUtils.renderJson(response, json);
	}
	
	/**
	 * 导出选中记录数
	 * */
	@RequestMapping("html/exportSel")
	public void exportSel(String ids, String colIds, String colNames, HttpServletResponse response) throws Exception {
		List<AppRole> list = appRoleService.getByIds(StringUtil.idStrToArr(ids, Long.class));
		
		String fname = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		response.setContentType("application/x-msdownload");
		response.setHeader("content-disposition","attachment; filename="+fname+".xls");
		ExportUtil.ExportXls(list, response.getOutputStream(), colIds, colNames);
	}
	
	/**
	 * 导出全部记录
	 * */
	@RequestMapping("html/exportAll")
	public void exportAll(String colIds, String colNames, 
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		List<StringPropertyFilter> filters = ExtjsUtil.getFilters(request);
		List<AppRole> list = appRoleService.search(filters);
		
		String fname = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		response.setContentType("application/x-msdownload");
		response.setHeader("content-disposition","attachment; filename="+fname+".xls");
		ExportUtil.ExportXls(list, response.getOutputStream(), colIds, colNames);
	}
	

}
